/**
 * @Author: likang xie
 * @Date: 2019-11-06 17:38:23
 * @Usage Request方法二次封装
 */

/**
 * @method openSetting 打开系统设置页面
 */
export let openSetting = () => {
  let device = uni.getSystemInfoSync();

  if (device.platform == "ios") {
    plus.runtime.openURL("app-settings:");
  } else {
    let main = plus.android.runtimeMainActivity();
    let Intent = plus.android.importClass("android.content.Intent");
    let Settings = plus.android.importClass("android.provider.Settings");

    let intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
    main.startActivity(intent);
  }
};

/**
 * @method getLocationInfo 获取位置信息
 * @return {Object} 位置信息
 */
export let getLocationInfo = () => {
  return new Promise((resolve, reject) => {
    // uni.showLoading({
    //   title: "正在获取..",
    //   mask: true,
    // });

    console.log("开始获取定位信息");

    uni.getLocation().then((chunk) => {
      let [err, res] = chunk;

      if (res) {
        let { latitude, longitude } = res;
        console.log("拿到定位信息：", res);
        uni.setStorageSync("location", res);

        // 根据经纬度换取城市信息
        console.log("开始获取位置信息");
        uni
          .request({
            url: `https://api.map.baidu.com/geocoder/v2/?ak=wWYw0yCb8ntXmSgTxTx40vKR&callback=renderReverse&output=json&pois=1&location=${[
              latitude,
              longitude,
            ].join(",")}`,
          })
          .then((chunk) => {
            uni.hideLoading();

            let [err, res] = chunk;

            if (res) {
              let realRes = {};
              let data = res.data;
              let str = data.split("renderReverse&&renderReverse(")[1];

              realRes = JSON.parse(str.substring(0, str.length - 1));
              console.log("拿到位置信息：", realRes);
              resolve(realRes);
            } else {
              uni.hideLoading();
              uni.showToast({
                title: "获取失败",
                icon: "none",
              });
              console.log("未拿到位置信息：", err);
              reject(err);
            }
          });
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "获取失败",
          icon: "none",
        });
        console.log("未拿到定位信息：", err);
        reject({ isAuth: false });
      }
    });
  });
};
